import { defineStore } from 'pinia';
import { type RouteLocationNormalized } from 'vue-router';
interface ITabbar {
  /** 标签页列表 */
  tabs: RouteLocationNormalized[];
}
function getTabPath (tab: RouteLocationNormalized) {
  return decodeURIComponent(tab.fullPath || tab.path);
}
export const useTabbarStore = defineStore('tabbar' , {
  state : (): ITabbar => ({
    tabs : []
  }),
  persist : [
    {
      key : 'tabs',
      storage : sessionStorage
    }
  ],
  actions : {
    /**
     * 添加tab
     * @param routeTab route路由对象
     */
    addTab (routeTab: RouteLocationNormalized) {
      const tabIndex = this.tabs.findIndex(tab => {
        return getTabPath(tab) === getTabPath(routeTab);
      });
      if (tabIndex === -1) {
        // 添加tab
        this.tabs.push(routeTab);
      }
    },
    /**
     * 关闭tab
     * @param routeTab route路由对象
     */
    closeTab (routeTab: RouteLocationNormalized) {
      const tabIndex = this.tabs.findIndex(tab => {
        return getTabPath(tab) === getTabPath(routeTab);
      });
      if (tabIndex > -1) {
        this.tabs.splice(tabIndex , 1);
      }
      return tabIndex;
    },
    /**
     * 更新tab
     * @param oldIndex 旧索引
     * @param newIndex 新索引
     */
    updateTab (oldIndex: number , newIndex: number) {
      const newTabs = [...this.tabs];
      const [deletedItem] = newTabs.splice(oldIndex, 1);
      newTabs.splice(newIndex, 0, deletedItem);
      this.tabs = newTabs;
    }
  }
});